<template>
    <el-dialog v-model="materVisible" width="815px" class="zw-materical-lib" @close="handleClose">
        <template #title>
            <div class="dialog_header">素材库选择</div>
        </template>

        <div class="tab_box">
            <div class="tab_header">
                <el-tabs v-model="baseId" class="base_tabs" @tab-change="tabClick">
                    <el-tab-pane v-for="item in tabs" :key="item.id" :label="item.name" :name="item.id"> </el-tab-pane>
                </el-tabs>
                <div class="tab_reset" @click="reset">刷新</div>
            </div>
            <div class="tab_content">
                <el-scrollbar v-if="![15, 11].includes(Number(baseId))" class="group_box">
                    <Grouping :tree-data="treeData" @submit="getChildGroup"></Grouping>
                </el-scrollbar>
                <div v-if="![15, 11].includes(Number(baseId))" class="line"></div>
                <div class="pane-box">
                    <ToggleType
                        v-if="baseId == 99 && types.includes(shopType)"
                        v-model="toggleType"
                        :is-goods-only="isGoodsOnly"
                        @select="selectToggleType" />
                    <SearchOfficialAccounts
                        v-if="baseId == 15"
                        v-model:title="officialAccountsParams.article_title"
                        v-model:id="officialAccountsParams.official_account_id"
                        @change="getList" />
                    <MinAppSearch
                        v-else-if="baseId == 11"
                        v-model:title="miniAppParams.title"
                        @change="getList"></MinAppSearch>
                    <el-input
                        v-else
                        v-model="keyword"
                        v-debounce="[getList]"
                        class="pane-box-input"
                        placeholder="搜索标题或文件名"
                        type="text"
                        :prefix-icon="Search"
                        clearable
                        @clear="clear">
                    </el-input>
                    <div
                        class="pane-body-box"
                        :class="{ 'pane-body-box-ecommerce': baseId == 99 && types.includes(shopType) }">
                        <keep-alive>
                            <div :key="randomKey">
                                <component
                                    :is="tabItem?.comName"
                                    v-if="tabItem?.comName"
                                    :multiple="multiple"
                                    :remain-num="remainNum"
                                    :base-list="baseList"
                                    :select-base-list="selectBaseList"
                                    :total-num="existFile"
                                    :infinite="infinite"
                                    :select-info-list="selectInfoList"
                                    @getData="getDataFun" />
                                <component
                                    :is="toggleType === 0 ? tabItem?.GoodsList : tabItem?.PageList"
                                    v-else
                                    :multiple="multiple"
                                    :remain-num="remainNum"
                                    :base-list="baseList"
                                    :select-base-list="selectBaseList"
                                    :total-num="existFile"
                                    :infinite="infinite"
                                    :select-info-list="selectInfoList"
                                    @getData="getDataFun" />
                            </div>
                        </keep-alive>
                    </div>
                    <div :key="randomKey2" class="pagination">
                        <ZWPagination v-if="tabItem?.comName" ref="PaginationRef1" @submit="getList" />
                        <ZWPagination v-else-if="toggleType === 0" ref="PaginationRef2" @submit="getList" />
                        <ZWPagination v-else-if="toggleType === 1" ref="PaginationRef3" @submit="getList" />
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="footer_box">
                <div class="left_footer">
                    <LeftFooter
                        v-show="baseId != 1 && !infinite"
                        :select-info-list="selectInfoList"
                        :total-num="existFile"
                        :select-num="selectNum"
                        :base-id="baseId"
                        :select-name-str="selectNameStr"
                        :remain-num="remainNum" />
                </div>
                <div class="right_footer">
                    <!-- 本地上传 -->
                    <template v-if="localUploadisShow.includes(baseId) && !disableUploadisShow.includes(baseId)">
                        <el-button v-if="baseId == 6" plain @click="showCreatLocalLink">创建链接</el-button>
                        <ZWUpload v-else ref="ZWUploadRef" :up-info="upInfo()" @submit="getUploadFile" />
                    </template>
                    <el-button v-else plain @click="handleClose">取消</el-button>
                    <el-button class="ml20" type="primary" @click="submitHandel">保存</el-button>
                </div>
            </div>
        </template>
    </el-dialog>

    <CreateLocalLink ref="CreateLocalLinkRef" @getLocalLink="getUploadFile" />
    <!-- 视频播放器 -->
    <VideoWicket ref="VideoWicketRef" />
</template>

<script lang="ts" setup>
import { ref, reactive, watch, shallowRef, computed } from 'vue';
import { useStore } from '@/store';
import { Search } from '@element-plus/icons-vue';
import { GetVideoList } from '@/api/media';
import {
    getGroupList,
    getVoiceList,
    getImageList,
    linkList,
    getFileList,
    getTextList,
    getGroupMarket,
    getCollectList,
    getMaterialStoreList,
    getGoodsList,
    getPageList
} from '@/api/concreation';
import { activityList } from '@/api/smartMarketing/luckyDraw';
import { getOfficialArticleList } from '@/api/content/channelFootage/officialaccountgraphics';
import { miniProgram } from '@/api/content/channelFootage/miniProgram';

import Grouping from './Grouping.vue';
import ZWPagination from '@/components/ZWPagination.vue';

import ImageList from './ImageList.vue';
import VideoList from './VideoList.vue';
import LinkList from './LinkList.vue';
import FileList from './fileList.vue';
import TextList from './TextList.vue';
import AudioList from './audioList.vue';
import CollectList from './CollectList.vue';
import GoodsList from './GoodsList.vue';
import PageList from './PageList.vue';
import OfficialAccounts from './OfficialAccounts.vue';
import MiniApp from './MiniApp.vue';

import LuckDraw from './luckDraw.vue';
import CreateLocalLink from './CreateLocalLink.vue';
import VideoWicket from './components/videoWicket.vue';
import LeftFooter from './components/LeftFooter.vue';

import ZWUpload from './ZWUpload.vue';
import ToggleType from './ToggleType.vue';

import SearchOfficialAccounts from './components/SearchOfficialAccounts.vue';
import MinAppSearch from './components/MinAppSearch.vue';

import { ElMessage } from 'element-plus';
import { deepClone } from '@/utils/utils';

import lodash from 'lodash';
const emit = defineEmits(['submit', 'submit2']);

const PaginationRef1 = ref<any>();
const PaginationRef2 = ref<any>();
const PaginationRef3 = ref<any>();

const store = useStore();
const CreateLocalLinkRef = ref<any>(null);
const showLuck = ref(false);
const keyword = ref('');
const materVisible = ref(false);
const groupId = ref(0);
const shopId = ref<number | string>('');
const shopType = ref<number | string>('1');

const baseId = ref<string | number>(''); // 图片
const infinite = ref<boolean>(false);
const isGoodsOnly = ref<boolean>(false);

const baseList = ref([]); // 列表
const existFile = ref<number>(9);
const selectName = ref<string | number>('2'); // 图片
const selectBaseList = ref([]);
const selectNameStr = ref<any>('文本');
const SOP = ref(false);
const localUploadisShow = ref(['1', '2', '3', '4', '5', '6']); // 是否显示本地上传按钮 默认名单
const disableUploadisShow = ref(['8', '27', '99']); // 是否显示本地上传按钮 排除名单

const tabItem = ref<any>();

type SearchType = {
    article_title: string;
    official_account_id: string;
};
const officialAccountsParams = reactive<SearchType>({
    article_title: '',
    official_account_id: ''
});
const miniAppParams = reactive({
    title: '',
    appid: '',
    page: 1,
    page_size: 15
});

// let officialAccountsParams_ = ref();

const toggleType = ref<number>(0);

const randomKey = ref<string>('');
const randomKey2 = ref<string>('');

const keyidaType = ref<string | number>('1');
const types = ref<any>(['1', '4']); // 1 客易达  2 有赞  3 淘宝  4 自营  5 线下门店

const paginationData = reactive<any>(null);

const showTabs = ref<any>([]);
const storesIds = ref<any>([]);

const multiple = ref<boolean>(true);

const multipleType = ref<number | string>('');

const selctInfo = ref({
    type: 0,
    typeStr: 'text',
    data: []
});

interface SelectInfoType {
    type: number | string;
    typeStr: string;
    data: any[];
}

const selectInfoList = reactive<Array<SelectInfoType>>([]);

//分组信息
const treeData = ref([]);
const upInfo = () => {
    switch (baseId.value) {
        case '1': // 文本
            return {
                type: 0,
                upFile: [],
                limitSize: 2,
                limitNum: 1,
                multiple: true,
                acceptFile: '.txt'
            };
        case '2': //图片
            return {
                type: 1,
                upFile: [],
                limitSize: 10,
                limitNum: remainNum.value,
                multiple: true,
                acceptFile: '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG'
            };
        case '3': // 音频
            return {
                type: 4,
                upFile: [],
                limitSize: 200,
                limitNum: 1,
                multiple: false,
                acceptFile: '.mp3,.wma,.wav,.amr,.m4a'
            };
        case '4': // 视频
            return {
                type: 2,
                upFile: [],
                limitSize: 10,
                limitNum: 1,
                multiple: false,
                acceptFile: '.mp4'
            };
        case '5': // 文件
            return {
                type: 5,
                upFile: [],
                limitSize: 20,
                limitNum: 1,
                multiple: false,
                acceptFile: '.DOC,.DOCX,.XLS,.XLSX,.CSV,.PPT,.PPTX,.TXT,.PDF,.Xmind'
            };
        default:
            return {
                type: 1,
                upFile: [],
                limitSize: 2,
                limitNum: 1,
                multiple: true,
                acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
            };
    }
};

// tabs
const tabs = ref([]);

const tabs2 = ref([
    { id: '2', type: 1, key: '1', name: '图片', nameStr: 'pic', total: 9, num: 0, comName: shallowRef(ImageList) },
    { id: '3', type: 4, key: '4', name: '音频', nameStr: 'audio', total: 9, num: 0, comName: shallowRef(AudioList) },
    { id: '4', type: 2, key: '2', name: '视频', nameStr: 'video', total: 9, num: 0, comName: shallowRef(VideoList) },
    { id: '5', type: 5, key: '5', name: '文件', nameStr: 'file', total: 9, num: 0, comName: shallowRef(FileList) },
    { id: '6', type: 3, key: '3', name: '链接', nameStr: 'link', total: 9, num: 0, comName: shallowRef(LinkList) },
    { id: '1', type: 0, key: '-1', name: '文本', nameStr: 'text', total: 1, num: 0, comName: shallowRef(TextList) },
    { id: '8', type: 6, key: '6', name: '抽奖', nameStr: 'luck', total: 9, num: 0, comName: shallowRef(LuckDraw) },
    {
        id: '27',
        type: 9,
        key: '6',
        name: '收集表',
        nameStr: 'collect',
        total: 9,
        num: 0,
        comName: shallowRef(CollectList)
    },
    {
        id: '99',
        type: 7,
        key: '9',
        name: '电商素材',
        nameStr: 'ecommerce',
        total: 9,
        num: 0,
        comName: null,
        GoodsList: shallowRef(GoodsList),
        PageList: shallowRef(PageList)
    },
    {
        id: '15',
        type: 10,
        key: '6',
        name: '公众号图文',
        nameStr: 'officialAccounts',
        total: 9,
        num: 0,
        comName: shallowRef(OfficialAccounts)
    },
    {
        id: '11',
        type: 11,
        key: '11',
        name: '小程序素材',
        nameStr: 'miniProgram',
        total: 9,
        num: 0,
        comName: shallowRef(MiniApp)
    }
]);

const getTabItemName = (num?: string | number) => {
    const id = num || baseId.value;
    selectNameStr.value = tabs.value.find((item: any) => item.id == id)?.name;
};

const tabClick = async (val?: any) => {
    PaginationRef1.value && (PaginationRef1.value.initPage = true);
    PaginationRef2.value && (PaginationRef2.value.initPage = true);
    PaginationRef3.value && (PaginationRef3.value.initPage = true);

    getTabItemName(val);
};

const handleClose = () => {
    selectInfoList.splice(0);
    selectBaseList.value = [];
    keyword.value = '';
    toggleType.value = 0;
    materVisible.value = false;
};
// 保存
const submitHandel = () => {
    store.dispatch('table', {
        tableData: [],
        tableAll: false
    });
    if (!selectInfoList.length) {
        ElMessage.error('请选择素材');
        return;
    }
    emit('submit', lodash.cloneDeep(selectInfoList));
    handleClose();
};

const selectToggleType = async (type: number): void => {
    keyword.value = '';
    toggleType.value = type;
    selctInfo.value.data = [];
    selectBaseList.value = [];
    await getList();
};

const selectNum = computed(() => {
    return selectInfoList.reduce((pre, cur) => {
        if (cur.data.length) {
            pre += cur.data.length;
        }
        return pre;
    }, 0);
});
const remainNum = computed(() => {
    if (existFile.value > selectNum.value) {
        return Number(existFile.value - selectNum.value);
    } else {
        return 0;
    }
});

// 素材库选的数据
const getDataFun = (data: any): void => {
    selctInfo.value = data;
    let index = 0;
    const targetItem = selectInfoList.find((item, ind) => {
        if (item.type == data.type) {
            index = ind;
            return true;
        } else {
            return false;
        }
    });

    if (targetItem) {
        if (multiple.value && baseId.value != 15) {
            if (data.deleteItem) {
                selectInfoList[index].data = selectInfoList[index].data.filter(ite => ite.id != data.deleteItem.id);
            } else {
                let arr = [];
                arr = data.data.filter(item => !targetItem.data.some(ite => ite.id == item.id));
                targetItem.data.push(...arr);
                selectInfoList.splice(index, 1, targetItem);
            }
        } else {
            selectInfoList[index].data.splice(0);
            if (data.data.length) {
                selectInfoList[index].data.push(...data.data);
            }
        }
    } else {
        selectInfoList.push(lodash.cloneDeep(data));
    }
};
// 本地数据
const getUploadFile = (data: any) => {
    if (data.type == 3) {
        data.local = true;
        data.type = 3;
        emit('submit', lodash.cloneDeep(data), true);
    } else {
        const type = tabs2.value.find(item => item.id == baseId.value)?.type || '1';
        const params = {
            local: true,
            // type: baseId.value,
            type,
            data
        };
        emit('submit', lodash.cloneDeep(params), true);
    }
    handleClose();
};

// 分组信息
const getGroupListData = async () => {
    let res: any[] = [],
        defaultId = 0;
    // 抽奖 分组
    if (baseId.value == 8) {
        res = await getGroupMarket({
            type: 13
        });
    } else if (baseId.value == 99) {
        let data = await getMaterialStoreList({ sub_num: 1 }); // sub_num  1 可以获取到对应店铺商品的总数
        const total = data.length;
        data = data.map(item => {
            const { sub_num: sub_num = 0 } = item;
            item.name = `${item.name} (${item.sub_num || 0})`;
            return item;
        });
        res = { data, total };
    } else {
        res = await getGroupList({
            type: baseId.value
        });
    }
    const result: any[] = [
        {
            name: '全部分组',
            id: 'all',
            nums: 0,
            children: []
        }
    ];
    if (res.data.length > 0) {
        result[0].nums = res.total;
        result[0].children = res.data;
        defaultId = res.data[0].id;
    }
    treeData.value = result;
    groupId.value = defaultId;
    shopId.value = defaultId;

    selctInfo.value.data = [];
    selectBaseList.value = [];
    if (baseId.value == 99) {
        if (storesIds.value?.length) {
            const filterData = filteTreeData(res.data);
            treeData.value = filterData;
            if (filterData?.length) {
                groupId.value = filterData[0]?.id;
                shopId.value = filterData[0]?.id;
            } else {
                groupId.value = '';
                shopId.value = '';
            }
        } else {
            treeData.value = res.data;
        }
        if (treeData.value?.length) {
            shopType.value = treeData.value[0]?.type;
        } else {
            shopType.value = '';
        }
    }
};
//  拿到分组的Id
const getChildGroup = async (val: number) => {
    selctInfo.value.data = [];
    selectBaseList.value = [];
    groupId.value = val;
    shopId.value = val;
    shopType.value = treeData.value.find(ite => ite.id == val)?.type || '';
    randomKey2.value = getRandomKey();
    toggleType.value = 0;
    await getList();
};
const getList = async (data?: any) => {
    let params = {
        title: keyword.value,
        keyword: keyword.value,
        goods_info: keyword.value,
        page_name: keyword.value,
        group_id: groupId.value,
        shop_id: shopId.value,
        page: data?.page || 1,
        page_size: data?.page_size || 15
    };

    let result = [],
        res = null;

    const type = Number(baseId.value);
    switch (type) {
        case 1: //文本
            res = await getTextList(params);
            break;
        case 2: //图片
            res = await getImageList(params);
            break;
        case 3: //语音
            res = await getVoiceList(params);
            break;
        case 4: // 视频
            res = await GetVideoList(params);
            break;
        case 5: // 文件
            res = await getFileList(params);
            break;
        case 6:
        case 7: // 链接
            res = await linkList(params);
            break;
        case 8: // 抽奖
            params.activity_status = 2;
            res = await activityList(params);
            break;
        case 27: // 收集表
            params.type = 2;
            res = await getCollectList(params);
            break;
        case 99: // 电商素材
            res = await getEcommerceList(params);
            break;
        case 15: // 公众号图文
            params.type = 2;
            params.publish_state = 2; // 发布状态 0-全部 1-发布中 2-发布成功 3-发布失败
            params = Object.assign({}, params, officialAccountsParams);
            res = await getOfficialArticleList(params);
            break;
        case 11: // 小程序
            miniAppParams.page = params.page;
            miniAppParams.page_size = params.page_size;
            params = Object.assign({}, miniAppParams);
            res = await miniProgram(params);
            break;
    }
    result = res?.data || [];
    store.dispatch('pageTotal', res?.total || 0);
    baseList.value = [];
    baseList.value = result;
    // baseList.value.forEach(item=>{
    //   item.isCheck = selectBaseList.value.some(ite => {
    //     if(ite.id == item.id && ite.tenant_id == item.tenant_id){
    //       ite.isCheck = true
    //       return true
    //     }else{
    //       return false
    //     }
    //   })
    // })
    selectBaseList.value = [];
    const targetItem = selectInfoList.find(item => item.id == baseId.value);
    if (targetItem && targetItem.data.length) {
        baseList.value.forEach(item => {
            item.isCheck = targetItem.data.some(ite => ite.id == item.id && ite.tenant_id == item.tenant_id);
            item.isCheck && selectBaseList.value.push(item);
        });
    }

    selectName.value = baseId.value;
    randomKey.value = getRandomKey();
};

const filteTreeData = (arr: any): void => {
    return arr.filter(item => {
        return storesIds.value.includes(item.id);
    });
};

const getEcommerceList = async (params: any) => {
    switch (toggleType.value) {
        case 0:
            params.goods_status = 2;
            params.stock_status = 1;
            return await getGoodsList(params);
        case 1:
            params.page_status = 1;
            return await getPageList(params);
    }
};
//本地上传
const showCreatLocalLink = () => {
    CreateLocalLinkRef.value.showDialog();
};
//点击搜索框x号
const clear = async () => {
    await getList();
};

const reset = async () => {
    await getList();
};

const getRandomKey = (num?: number) => {
    const t = 'ABCDEFGHJKMNPQRSTWXYZ0123456789abcdefhijkmnprstwxyz?_*%$#';
    let total = '';
    let n = 0;
    if (typeof num === 'number' && num > 0 && num < 21) {
        while (n < num) {
            const add = t[Math.round(Math.random() * Number(t.length - 1))];
            total = `${total}${add}`;
            n++;
        }
    } else {
        total = getRandomKey(16);
    }
    return total;
};

defineExpose({
    materVisible,
    baseId,
    existFile,
    showLuck,
    SOP,
    tabs,
    localUploadisShow,
    showTabs,
    multiple,
    storesIds,
    infinite,
    isGoodsOnly,
    multipleType
});

watch(
    showTabs,
    (val: any) => {
        if (val?.length) {
            tabs.value = tabs2.value.filter((item: any) => val.includes(item.id));
        }
        tabClick();
    },
    { deep: true, immediate: true }
);

watch(
    baseId,
    async (val: any) => {
        tabItem.value = tabs.value.find(item => item.id == val);
        // 目前 公众号图文 只支持单选
        // if(val == 15){
        //   multiple.value = false
        // }
        if (multipleType.value) {
            if (multipleType.value == val) {
                multiple.value = true;
            } else {
                multiple.value = false;
            }
        }

        if (val) {
            if (!['11', '15'].includes(val)) {
                await getGroupListData();
            }
            await getList();
        }
    },
    { immediate: true }
);
</script>

<style lang="scss">
.zw-materical-lib {
    .el-dialog__body {
        padding: 0;
    }
}
</style>

<style lang="scss" scoped>
.tab_box {
    min-height: 500px;

    // position: relative;
    .tab_header {
        width: 100%;
        display: flex;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 12px;
        position: relative;
        margin-bottom: 10px;

        &::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            width: 100%;
            height: 2px;
            background-color: #eee;
        }

        .base_tabs {
            width: 92%;

            // background: #f9f9f9;
            :deep .el-tabs__header {
                margin: 0;

                .el-tabs__nav-wrap {
                    &::after {
                        height: 0;
                    }
                }
            }

            padding: 0 10px;
            box-sizing: border-box;
        }

        .tab_reset {
            width: 8%;
            text-align: center;
            white-space: nowrap;
            line-height: 38px;
            height: 38px;
            color: #ff6b00;

            // background: #f9f9f9;
            // border-bottom: 2px solid #E3E7ED;
            &:hover {
                cursor: pointer;
                color: #f99032;
            }
        }
    }

    .tab_content {
        display: flex;

        .group_box {
            padding-bottom: 8px;
            box-sizing: border-box;
            width: 170px;
            height: 514px;
            background: #fff;
        }

        .line {
            width: 2px;
            background-color: #eee;
            margin: 0 0 8px 6px;
        }

        .pane-box {
            max-height: 514px;
            flex: 1;
            padding: 8px 16px;
            box-sizing: border-box;

            .pane-box-input {
                margin-bottom: 12px;
            }

            .pagination {
                // padding-bottom: 10px;
            }

            .pane-body-box {
                // margin-top: 12px;
                // width: 100%;
                height: 404px;
                overflow-y: scroll;
                white-space: nowrap;
            }

            .pane-body-box-ecommerce {
                height: calc(404px - 54px);
            }

            .pane-body-box-public {
                height: calc(404px + 52px);
            }

            .pane-body-box::-webkit-scrollbar {
                width: 0 !important;
            }

            .pane-body-box::-webkit-scrollbar {
                width: 0 !important;
                height: 0;
            }

            :deep .el-pagination__sizes {
                margin-right: -10px;
            }
        }
    }
}

.footer_box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left_footer {
        flex: 1;
        text-align: left;
        margin-right: 12px;
    }

    .right_footer {
        display: flex;
    }
}

.ml20 {
    margin-left: 20px;
}
</style>
